package com.cloud.wms.ui.data.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.ScanText;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.CacheConfig;
import com.cloud.wms.ui.data.contract.UploadImgContract;
import com.cloud.wms.ui.data.presenter.UploadImgPresenter;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;
import com.squareup.picasso.Picasso;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-21 15:36
 * @Description:
 */
public class UploadImgActivity extends BaseBarListActivity<String, UploadImgPresenter> implements UploadImgContract.View {
    private static final int REQUEST_CODE = 0x1001;
    private static final CharSequence[] items = {"到货登记", "出库拍照"};
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private static final int MAX_IMG_COUNT = 9;
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.tv_type)
    TextView tvType;
    private int mImageResize;
    private static final String ADD_TAG = "IMG";
    private String orderCode;
    private String typeCode;
    private AlertDialogBuilder itemsDialog;

    @Override
    protected String barTitle() {
        return "拍照上传";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_common_upload_img;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_select_photo;
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initScanText(scanText);
        btnSubmit.setEnabled(false);
        ArrayList<String> list = new ArrayList<>();
        list.add(ADD_TAG);
        mAdapter.setNewInstance(list);
        mAdapter.addChildClickViewIds(R.id.iv_delete);

        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mAdapter.removeAt(position);
            if (!ADD_TAG.equals(mAdapter.getData().get(mAdapter.getData().size() - 1))) {
                mAdapter.addData(ADD_TAG);
            }
            if (mAdapter.getData().size() <= 1) {
                btnSubmit.setEnabled(false);
            }
        });

        typeSelectDialog(null);
    }

    private void typeSelectDialog(String scanCode) {
        if (itemsDialog == null) {
            itemsDialog = (AlertDialogBuilder) new AlertDialogBuilder(this)
                    .setCancelable(false)
                    .setTitle("选择单据类型")
                    .setPositiveButton(
                            "确定",
                            (DialogInterface dialog, int which) -> {
                                int checkedItemPosition =
                                        ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                                if (checkedItemPosition != AdapterView.INVALID_POSITION) {
                                    tvType.setText(items[checkedItemPosition]);
                                    if (TextUtils.isEmpty(scanCode)) {
                                        typeCode = checkedItemPosition + "";
                                    } else {
                                        mPresenter.checkOrderCode(scanCode, typeCode);
                                    }
                                }
                            })
                    .setSingleChoiceItems(items, 0, null);
        }
        itemsDialog.show();
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        orderCode = result;
        if (TextUtils.isEmpty(typeCode)) {
            typeSelectDialog(result);
            return;
        }
        mPresenter.checkOrderCode(result, typeCode);
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, String item) {
        helper.setGone(R.id.iv_delete, item.equals(ADD_TAG));
        ImageView imageView = (ImageView) helper.getView(R.id.iv_select_photo);
        int resize = getItemResize();
        if (!item.equals(ADD_TAG))
            Picasso.with(this).load("file://" + item)
                    .placeholder(R.mipmap.icon_image_holder)
                    .resize(resize, resize)
                    .centerCrop()
                    .into(imageView);
        else
            Picasso.with(this).load("file://" + item)
                    .placeholder(R.mipmap.icon_picture_add)
                    .into(imageView);
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(this, 2);
    }

    @Override
    protected RecyclerView.ItemDecoration itemDecoration() {
        return GridItemDecoration.newBuilder().spanCount(2)
                .verticalDivider(ContextCompat.getDrawable(this, R.color.white), DensityUtils.Dp2Px(this, 6), false)
                .horizontalDivider(ContextCompat.getDrawable(this, R.color.white), DensityUtils.Dp2Px(this, 6), false)
                .build();
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<String, BaseViewHolder> mAdapter, View view, int position) {
        super.itemClickListener(mAdapter, view, position);
        if (TextUtils.isEmpty(orderCode)) {
            info("请先扫描单据号");
            return;
        }

        if (TextUtils.isEmpty(typeCode)) {
            info("请先选择对应单据类型");
            return;
        }

        if (ADD_TAG.equals(mAdapter.getData().get(position)) && MAX_IMG_COUNT > mAdapter.getData().size() - 1) {
            selectPhoto(mAdapter.getData().size() - 1);
        }
    }

    @Override
    public void onSuccess(Message message) {
        super.onSuccess(message);
        switch (message.what) {
            case UploadImgPresenter.ORDER_CHECK:
                info("请选择需上传的图片");
                break;
            case UploadImgPresenter.IMG_UPLOAD:
                success("上传成功！");
                this.finish();
                break;
        }
    }

    @OnClick({R.id.tv_type, R.id.iv_type, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_type:
            case R.id.iv_type:
                typeSelectDialog(orderCode);
                break;
            case R.id.btn_submit:
                verifySubmit();
                break;
        }
    }

    private void verifySubmit() {
        if (TextUtils.isEmpty(orderCode)) {
            info("请先扫描单据号");
            return;
        }

        if (TextUtils.isEmpty(typeCode)) {
            info("请先选择对应单据类型");
            return;
        }

        if (mAdapter.getData().size() <= 1) {
            info("请选择需要上传的图片");
            return;
        }

        ArrayList<String> list = new ArrayList<>(mAdapter.getData());
        if (mAdapter.getData().size() < MAX_IMG_COUNT)
            list.remove(list.size() - 1);

        mPresenter.uploadImg(
                orderCode,
                typeCode,
                list);
    }

    private int getItemResize() {
        if (mImageResize == 0) {
            RecyclerView.LayoutManager lm = rvList.getLayoutManager();
            int spanCount = ((GridLayoutManager) lm).getSpanCount();
            int screenWidth = this.getResources().getDisplayMetrics().widthPixels;
            int availableWidth = screenWidth - 6 * (spanCount - 1);
            mImageResize = availableWidth / spanCount;
        }
        return mImageResize;
    }

    private void selectPhoto(int size) {
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, CacheConfig.AUTHORITY))
                .maxSelectable(MAX_IMG_COUNT - size)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new PicassoEngine())
                .showSingleMediaType(true)
                .originalEnable(true)
                .maxOriginalSize(10)
                .autoHideToolbarOnSingleTap(true)
                .theme(R.style.Matisse_Dracula)
                .forResult(REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            List<String> imagePaths = Matisse.obtainPathResult(data);
            List<String> adapterData = mAdapter.getData();
            adapterData.remove(adapterData.size() - 1);
            adapterData.addAll(imagePaths);
            if (adapterData.size() < MAX_IMG_COUNT) {
                adapterData.add(ADD_TAG);
            }
            mAdapter.notifyDataSetChanged();
            btnSubmit.setEnabled(true);
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, UploadImgActivity.class);
        context.startActivity(intent);
    }
}
